package com.fnzn.entranceGuard.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fnzn.entranceGuard.bean.UnitHouseBean;
import com.fnzn.entranceGuard.constant.GuardConstant;
import com.fnzn.entranceGuard.entity.GuardDevice;
import com.fnzn.entranceGuard.entity.GuardIcDevice;
import com.fnzn.entranceGuard.entity.GuardIcInfo;
import com.fnzn.entranceGuard.entity.QR;
import com.fnzn.entranceGuard.mapper.GuardDeviceMapper;
import com.fnzn.entranceGuard.mapper.GuardIcDeviceMapper;
import com.fnzn.entranceGuard.mapper.GuardIcInfoMapper;
import com.fnzn.entranceGuard.rest.guard.ScanUtil;
import com.fnzn.entranceGuard.rest.guard.UsrUtil;
import com.fnzn.entranceGuard.rest.usrCloud.UsrApi;
import com.fnzn.entranceGuard.service.IGuardIcDeviceService;
import com.fnzn.entranceGuard.util.QRGenerate;
import com.fnzn.entranceGuard.vo.GuardDeviceVo;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ListUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * IC设备关联 服务实现类
 * </p>
 *
 * @author JokerGao
 * @since 2018-08-24
 */
@Service
public class GuardIcDeviceServiceImpl extends ServiceImpl<GuardIcDeviceMapper, GuardIcDevice> implements IGuardIcDeviceService {

    @Autowired
    private GuardIcDeviceMapper guardIcDeviceMapper;
    @Autowired
    private GuardDeviceMapper guardDeviceMapper;
    @Autowired
    private GuardIcInfoMapper guardIcInfoMapper;

    /**
     * 同步
     * @param guardIcInfo
     * @return
     */
    @Override
    public ResponseUtil updateStatusByIcInfoId(GuardIcInfo guardIcInfo) {
        ResponseUtil responseUtil = new ResponseUtil();
        try{
            String icInfoId = guardIcInfo.getId();
            Integer deviceId = guardIcInfo.getDeviceId();
            guardIcDeviceMapper.updateStatusByIcInfoIdAndDeviceId(icInfoId, deviceId);
                String deviceNumber = guardIcInfo.getDeviceNumber();//设备号
                String type = guardIcInfo.getType();//设备类型
                if(deviceNumber != null && !"".equals(deviceNumber)) {
                    //先查看设备在不在线
                    if (UsrApi.getDevice(deviceNumber)) {
                        List<GuardIcInfo> guardIcInfoList = new ArrayList<>();
                        guardIcInfoList.add(guardIcInfo);
                        boolean flag;
                        if(StringUtils.isNotBlank(guardIcInfo.getHouseOwnerId())) {
                            flag = UsrUtil.addOrDelIcToDev(guardIcInfoList, deviceNumber, GuardConstant.TYPE_ADD, type, null);
                        } else {
                            flag = UsrUtil.addOrDelIcToDev(guardIcInfoList, deviceNumber, GuardConstant.TYPE_ADD, type, "Admin");
                        }
                        if(flag) {
                            responseUtil.setStatus(ResponseUtil.SUCCESS);
                            responseUtil.setMsg("正在同步");
                        }else {
                            responseUtil.setStatus(ResponseUtil.ERROR);
                            responseUtil.setMsg("插入设备出错同步失败");
                        }
                    } else{
                        responseUtil.setStatus(ResponseUtil.ERROR);
                        responseUtil.setMsg("设备不在线！");
                    }
                } else {
                    responseUtil.setStatus(ResponseUtil.ERROR);
                    responseUtil.setMsg("删除失败，设备为空");
                }
        }catch (Exception e){
            e.printStackTrace();
            responseUtil.setStatus(ResponseUtil.ERROR);
            responseUtil.setMsg("同步失败");
        }
        return responseUtil;
    }

    /**
     * 通过房屋同步（房屋所有业主下的Ic卡）
     * @param houseId
     * @return
     */
    @Override
    public ResponseUtil updateStatusByHouseId(String houseId) {
        ResponseUtil responseUtil = new ResponseUtil();
        try{
            List<GuardIcInfo> guardIcInfos = guardIcInfoMapper.selectByHouseId(houseId);
            if (!ListUtils.isEmpty(guardIcInfos)) {
                for(GuardIcInfo guardIcInfo: guardIcInfos) {
                    String icInfoId = guardIcInfo.getId();
                    guardIcDeviceMapper.updateStatusByIcInfoId(icInfoId);
                    List<GuardDeviceVo> list = guardIcDeviceMapper.getByIcInfoId(icInfoId);
                    if (list != null) {
                        String deviceId;//设备号
                        String type;//设备类型
                        for (GuardDeviceVo guardDeviceVo : list) {
                            deviceId = guardDeviceVo.getDeviceNumber();
                            type = guardDeviceVo.getType();
                            if (deviceId == null && "".equals(deviceId)) {
                                break;
                            }
                            //先查看设备在不在线
                            if (UsrApi.getDevice(deviceId)) {
                                List<GuardIcInfo> guardIcInfoList = new ArrayList<>();
                                guardIcInfoList.add(guardIcInfo);
                                boolean flag = UsrUtil.addOrDelIcToDev(guardIcInfoList, deviceId, GuardConstant.TYPE_ADD, type, null);
                                if (flag) {
                                    responseUtil.setStatus(ResponseUtil.SUCCESS);
                                    responseUtil.setMsg("正在同步");
                                } else {
                                    responseUtil.setStatus(ResponseUtil.ERROR);
                                    responseUtil.setMsg("插入设备出错同步失败");
                                }
                            } else {
                                responseUtil.setStatus(ResponseUtil.ERROR);
                                responseUtil.setMsg("设备不在线！");
                            }
                        }
                    } else {
                        responseUtil.setStatus(ResponseUtil.ERROR);
                        responseUtil.setMsg("同步失败，无此设备！");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            responseUtil.setStatus(ResponseUtil.ERROR);
            responseUtil.setMsg("同步失败");
        }
        return responseUtil;
    }

    @Override
    public void updateStatus(String deviceNumber, byte[] icIds, Integer state) {
        try {
            List<GuardDevice> guardDevices = guardDeviceMapper.selectByDeviceId(deviceNumber);
            //deviceId关联Id
            Integer id =null;
            if(guardDevices.size()>0){
               id  = guardDevices.get(0).getId();
            }
            String status = "";
            if(state == 1){
                status = GuardConstant.SYNC_SUCCESS;
            } else if(state == 0) {
                status = GuardConstant.SYNC_DEFEAT;
            }

            String icInfoIds = QRGenerate.parse16Byte2Str(icIds);
            String icId;
            GuardIcInfo guardIcInfo = new GuardIcInfo();
            guardIcInfo.setDelFlag(CommonConstant.STATUS_NORMAL);
            for(int i=0; i < icInfoIds.length()/8; i++){
                icId = icInfoIds.substring(i * 8, (i + 1) * 8);
                guardIcInfo.setIcId(icId.toUpperCase());
                guardIcInfo = guardIcInfoMapper.selectOne(guardIcInfo);
                if(guardIcInfo != null) {
                    guardIcDeviceMapper.updateStatusByDeviceIdAndIcInfoId(id, guardIcInfo.getId(), status);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteIcDevice(String deviceNumber, byte[] icIds, Integer state) {
        try {
            List<GuardDevice> guardDevices = guardDeviceMapper.selectByDeviceId(deviceNumber);
            //deviceId关联Id
            Integer id = null;
            if(guardDevices.size()>0){
                id  = guardDevices.get(0).getId();
            }
            String status = "";
            if(state == 1){//成功
                String icInfoIds = QRGenerate.parse16Byte2Str(icIds);
                String icId;//IC卡号
                GuardIcInfo guardIcInfo = new GuardIcInfo();
                guardIcInfo.setDelFlag(CommonConstant.STATUS_NORMAL);
                for(int i=0; i < icInfoIds.length()/8; i++){
                    icId = icInfoIds.substring(i * 8, (i + 1) * 8);
                    guardIcInfo.setIcId(icId.toUpperCase());
                    guardIcInfo = guardIcInfoMapper.selectOne(guardIcInfo);
                    if(guardIcInfo!=null){
                        String guardIcInfoId = guardIcInfo.getId();//主键ID
                        List<GuardIcDevice> guardIcDevices = guardIcDeviceMapper.selectByGuardIcInfoId(guardIcInfoId);
                        int flag = 0;
                        if (guardIcDevices != null) {
                            for(GuardIcDevice guardIcDevice: guardIcDevices) {
                                if(guardIcDevice.getStatus().equals(GuardConstant.DEAD_STATUS)) {
                                    flag++;
                                }
                            }
                        }
                        if(flag == 0) {
                            guardIcDeviceMapper.deleteByIcInfoIdAndDeviceId(guardIcInfoId, id);//关联表删除
                            List<GuardIcDevice> guardIcDeviceList = guardIcDeviceMapper.selectByGuardIcInfoId(guardIcInfoId);
                            if (ListUtils.isEmpty(guardIcDeviceList)) {
                                guardIcInfo.setUpdateTime(new Date());
                                guardIcInfo.setDelFlag(CommonConstant.STATUS_DEL);
                                guardIcInfoMapper.updateById(guardIcInfo);
                            }
                        }
                    }
                }
            } else if(state == 0) {//失败
                status = GuardConstant.SYNC_SUCCESS;
                String icInfoIds = QRGenerate.parse16Byte2Str(icIds);
                String icId;
                GuardIcInfo guardIcInfo = new GuardIcInfo();
                guardIcInfo.setDelFlag(CommonConstant.STATUS_NORMAL);
                for(int i=0; i < icInfoIds.length()/8; i++){
                    icId = icInfoIds.substring(i * 8, (i + 1) * 8);
                    guardIcInfo.setIcId(icId.toUpperCase());
                    guardIcInfo = guardIcInfoMapper.selectOne(guardIcInfo);
                    if(guardIcInfo!=null) {
                        guardIcDeviceMapper.updateStatusByDeviceIdAndIcInfoId(id, guardIcInfo.getId(), status);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//        String a = "123456789012";
//        String b = a.substring(0,1);
//        String d = "";
//        for(int i=0;i<a.length()/4;i++){
//
//
//            System.out.println(a.substring(i * 4, (i + 1) * 4));
//
//
//        }

//        char[] chars = icInfoIds.toCharArray();
//        StringBuffer sb = new StringBuffer();
//        for(int i = 0; i < icIds.length; i++) {
//            if(i % 8 == 7){
//                sb.append(chars);
//                guardIcDeviceMapper.updateStatusByDeviceIdAndIcInfoId(id, sb.toString(), status);
//                sb.setLength(0);
//            }else{
//                sb.append(chars);
//            }
//        }
        byte[] b = {0x5e,0x0e,-101,0x02,0x5e,0x5e};
        try {
            System.out.println(QRGenerate.parse16Byte2Str(b));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
